package com.yuelao.yuelao_backend.controller;

import com.yuelao.yuelao_backend.common.ApiResponse;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.entity.SystemMessage;
import com.yuelao.yuelao_backend.service.SystemMessageService;
import com.yuelao.yuelao_backend.util.UserContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统消息Controller
 */
@RestController
@RequestMapping("/system-messages")
@Slf4j
@RequiredArgsConstructor
public class SystemMessageController {

    private final SystemMessageService systemMessageService;

    /**
     * 获取系统消息列表
     * GET /system-messages
     * @param page 页码
     * @param size 每页数量
     * @return 系统消息列表
     */
    @GetMapping
    public ApiResponse<Map<String, Object>> getSystemMessages(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Long userId = UserContextUtil.getCurrentUserId();
        
        List<SystemMessage> messages = systemMessageService.getUserMessages(userId, page, size);
        long total = systemMessageService.count();
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", messages);
        result.put("total", total);
        
        return ApiResponse.ok(result);
    }

    /**
     * 标记系统消息为已读
     * PUT /system-messages/{messageId}/read
     * @param messageId 消息ID
     * @return 是否成功
     */
    @PutMapping("/{messageId}/read")
    public ApiResponse<Boolean> markAsRead(@PathVariable Long messageId) {
        if (messageId == null || messageId <= 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "消息ID无效");
        }
        
        Long userId = UserContextUtil.getCurrentUserId();
        boolean result = systemMessageService.markAsRead(messageId, userId);
        
        return ApiResponse.ok(result);
    }

    /**
     * 全部标记为已读
     * PUT /system-messages/read-all
     * @return 是否成功
     */
    @PutMapping("/read-all")
    public ApiResponse<Boolean> markAllAsRead() {
        Long userId = UserContextUtil.getCurrentUserId();
        boolean result = systemMessageService.markAllAsRead(userId);
        
        return ApiResponse.ok(result);
    }

    /**
     * 获取未读消息数量
     * GET /system-messages/unread-count
     * @return 未读数量
     */
    @GetMapping("/unread-count")
    public ApiResponse<Map<String, Object>> getUnreadCount() {
        Long userId = UserContextUtil.getCurrentUserId();
        long count = systemMessageService.getUnreadCount(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("count", count);
        
        return ApiResponse.ok(result);
    }
}

